<?php
//@set_time_limit(0);
////error_reporting(E_ALL || ~E_NOTICE);
//
//$verMsg = 'MaCms V1.0 UTF8';
//$errmsg = '';
//$insLockfile = dirname(__FILE__).'/install_lock.txt';
//$moduleCacheFile = dirname(__FILE__).'/modules.tmp.inc';
@set_time_limit(0);
define('WEBROOT', preg_replace("/install/", '', dirname(__FILE__)));

require_once(WEBROOT . '/include/common.inc.php');

$_POST['action'] = empty($_POST['action']) ? '' : $_POST['action'];
$_GET['action'] = empty($_GET['action']) ? '' : $_GET['action'];
$action = empty($_GET['action']) ? $_POST['action'] : $_GET['action'];
$step = empty($_GET['step']) ? '1' : $_GET['step'];
$dbinfo = $db[$TmacConfig['Common']['Database']];
if ((!empty($action) && $action != 'createConfigFile' && $action != 'chkdname' && $action != 'sdname') || ($step != 1 && $step != 2)) {
    if (empty($dbinfo['password']) || empty($dbinfo['database'])) {
        header('Location:index.php');
        exit();
    } else {
        //生成数据库操作实例
        $db = new DB($dbinfo['hostname'], $dbinfo['username'], $dbinfo['password'], $dbinfo['database'], $dbinfo['char_set'], $dbinfo['dbprefix']);
    }
}
require_once(WEBROOT . '/install/install.inc.php');

$insLockfile = ROOTDATA . 'install.lock';
if (file_exists($insLockfile)) {
    exit(" 程序已运行安装，如果你确定要重新安装，请先从FTP中删除 install.lock 文件");
}

$s_lang = $TmacConfig['config']['soft_lang'];
$dfDbname = strtolower(str_replace(array('_', '.'), '', $TmacConfig['config']['soft_enname'].$TmacConfig['config']['version']));

$verLockFile = VAR_ROOT . '/Data/ver.txt';
$fp = fopen($verLockFile, 'r');
$upTime = trim(fread($fp, 64));
fclose($fp);

//require_once(DEDEINC.'/common.func.php');
//查询有多少数据库
if ($action == 'sdname') {
    $dbhost = empty($_POST['dbhost']) ? '' : $_POST['dbhost'];
    $dbuser = empty($_POST['dbuser']) ? '' : $_POST['dbuser'];
    $dbpwd = empty($_POST['dbpwd']) ? '' : $_POST['dbpwd'];
    $rs = get_db_list($dbhost, $dbuser, $dbpwd);
    if ($rs === false)
        exit('errorpwd');
    foreach ($rs AS $k => $v) {
        $json[] = $v;
    }
    $a = json_encode($json);
    exit($a);
}
//检测数据库连接是否正确
elseif ($action == 'chkdname') {
    $dbhost = empty($_POST['dbhost']) ? '' : $_POST['dbhost'];
    $dbuser = empty($_POST['dbuser']) ? '' : $_POST['dbuser'];
    $dbpwd = empty($_POST['dbpwd']) ? '' : $_POST['dbpwd'];
    $conn = @mysql_connect($dbhost, $dbuser, $dbpwd);

    if ($conn === false) {
        exit('0');
    } else {
        exit('1');
    }
}
//创建配置文件
elseif ($action == 'createConfigFile') {
    $dbhost = empty($_POST['dbhost']) ? '' : $_POST['dbhost'];
    $dbuser = empty($_POST['dbuser']) ? '' : $_POST['dbuser'];
    $dbpwd = empty($_POST['dbpwd']) ? '' : $_POST['dbpwd'];
    $dbname = empty($_POST['dbname']) ? '' : $_POST['dbname'];
    $dbprefix = empty($_POST['dbprefix']) ? '' : $_POST['dbprefix'];
    $dblang = empty($_POST['dblang']) ? '' : $_POST['dblang'];
    $info = create_config_file($dbhost, $dbuser, $dbpwd, $dbname, $dbprefix, $dblang);
    $json['rs'] = $info['rs'];
    $json['info'] = $info['msg'];
    $jsons = json_encode($json);
    exit($jsons);
    die;
}
//初始化数据库
elseif ($action == 'createDatabase') {
    global $errinfo;
    $dbhost = empty($_POST['dbhost']) ? '' : $_POST['dbhost'];
    $dbuser = empty($_POST['dbuser']) ? '' : $_POST['dbuser'];
    $dbpwd = empty($_POST['dbpwd']) ? '' : $_POST['dbpwd'];
    $dbname = empty($_POST['dbname']) ? '' : $_POST['dbname'];
    $dbprefix = empty($_POST['dbprefix']) ? '' : $_POST['dbprefix'];
    $dblang = empty($_POST['dblang']) ? '' : $_POST['dblang'];
    $rs = create_database($dbhost, $dbuser, $dbpwd, $dbname, $dbprefix, $dblang);
    if ($rs) {
        $rs = 1;
        $info = '数据库创建';
    } else {
        $rs = 0;
        $info = $errinfo;
    }

    $json['rs'] = $rs;
    $json['info'] = $info;
    $jsons = json_encode($json);
    exit($jsons);
    die;
}
//安装表节构
elseif ($action == 'installBaseData') {
    $bkdir = ROOTDATA . 'installsql';
    if (!$dh = @dir($bkdir)) {
        $json['rs'] = 0;
        $json['msg'] = '没找到的安装数据库初始数据文件,请联系技术人员, 或重新下载最新安装!';
        $jsons = json_encode($json);
        exit($jsons);
        die;
    }

    while (($filename = $dh->read()) !== false) {
        if (!preg_match('/txt$/', $filename)) {
            continue;
        }
        if (preg_match('/tables_struct/', $filename)) {
            $structfile = $filename;
        } else if (filesize("$bkdir/$filename") > 0) {
            $filelists[] = $filename;
        }
    }

    $dh->close();

    $filelist_string = implode(',', $filelists);
//    debugAjax($filelist_string);
    $info = doRevertData($bkdir, $filelist_string, $structfile);
    if (count($info) == 3) {
        $rs = 1;
        $startgo = $info['startgo'];
        $bakfiles = $info['bakfiles'];
    } else {
        $rs = 0;
        $startgo = $info['startgo'];
        $bakfiles = '';
    }

    $json['rs'] = $rs;
    $json['startgo'] = $startgo;
    $json['bakfiles'] = $bakfiles;
    $json['msg'] = $info['msg'];
    $jsons = json_encode($json);
    exit($jsons);
    die;
}
//安装表数据
elseif ($action == 'installBaseData_table') {
    $bkdir = ROOTDATA . 'installsql';
    if (empty($_POST['bakfiles'])) {
        $json['where'] = 'bakfiles_error';
        $json['msg'] = "出错了bakfiles参数为空,请重试安装程序";
        $jsons = json_encode($json);
        exit($jsons);
        die;
    }
    if (empty($_POST['startgo'])) {
        $json['where'] = 'startgo_error';
        $json['msg'] = "出错了startgo参数为空,请重试安装程序";
        $jsons = json_encode($json);
        exit($jsons);
        die;
    }
    $startgo = $_POST['startgo'];
    $bakfiles = $_POST['bakfiles'];

    $info = doRevertData($bkdir, $bakfiles, $structfile = '', $startgo);

    $json['where'] = $info['where'];
    $json['startgo'] = $info['startgo'];
    $json['bakfiles'] = $info['bakfiles'];
    $json['msg'] = $info['msg'];
    $jsons = json_encode($json);
    exit($jsons);
    die;
}




/* ------------------------
  环境测试
  function _1_TestEnv()
  ------------------------ */
if ($step == 1) {
    $phpv = phpversion();
    $sp_os = @getenv('OS');
    $sp_gd = gdversion();
    $sp_server = $_SERVER['SERVER_SOFTWARE'];
    $sp_host = (empty($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_HOST'] : $_SERVER['REMOTE_ADDR']);
    $sp_name = $_SERVER['SERVER_NAME'];
    $sp_max_execution_time = ini_get('max_execution_time');
    $sp_allow_reference = (ini_get('allow_call_time_pass_reference') ? '<font color=green>[√]On</font>' : '<font color=red>[×]Off</font>');
    $sp_allow_url_fopen = (ini_get('allow_url_fopen') ? '<font color=green>[√]On</font>' : '<font color=red>[×]Off</font>');
    $sp_safe_mode = (ini_get('safe_mode') ? '<font color=red>[×]On</font>' : '<font color=green>[√]Off</font>');
    $sp_gd = ($sp_gd > 0 ? '<font color=green>[√]On</font>' : '<font color=red>[×]Off</font>');
    $sp_mysql = (function_exists('mysql_connect') ? '<font color=green>[√]On</font>' : '<font color=red>[×]Off</font>');

    if ($sp_mysql == '<font color=red>[×]Off</font>') {
        $sp_mysql_err = true;
    } else {
        $sp_mysql_err = false;
    }

    $sp_testdirs = array(
        '',
        'application/*',
        'var/*',
        'wwwroot/*'
    );
    include('./templates/step-1.html');
    exit();
}
/* ------------------------
  数据库测试安装
  function _2_TestEnv()
  ------------------------ */ else if ($step == 2) {
    if (empty($_SERVER['HTTP_HOST'])) {
        $baseurl = 'http://' . $_SERVER['HTTP_HOST'];
    } else {
        $baseurl = "http://" . $_SERVER['SERVER_NAME'];
    }

    include('./templates/step-2.html');
    exit();
}

/* ------------------------
  普通安装
  function _3_Setup()
  ------------------------ */ else if ($step == 3) {
    checkdatabase();
    include('./templates/step-3.html');
    exit();
}

/* ------------------------
  保存安装数据
  function _4_Setup()
  ------------------------ */ else if ($step == 4) {
    if (empty($_POST['agent_id'])) {
        redirect('请填写联盟ID！');
    }
    if (empty($_POST['agent_md'])) {
        redirect('请填写联盟加密字符串！');
    }
    if (empty($_POST['agent_postmd'])) {
        redirect('请填写订单保存KEY！');
    }
    if (empty($_POST['cfg_webname'])) {
        redirect('请填写设置网站名称！');
    }
    if (empty($_POST['cfg_indexurl'])) {
        redirect('请填写网站域名！');
    }
    if (empty($_POST['username'])) {
        redirect('请填写用户名！');
    }
    if (empty($_POST['password'])) {
        redirect('请填写密码！');
    }
    $agent_id = trim($_POST['agent_id']);
    $agent_md = trim($_POST['agent_md']);
    $agent_postmd = trim($_POST['agent_postmd']);
    $cfg_webname = trim($_POST['cfg_webname']);
    $cfg_indexurl = trim($_POST['cfg_indexurl']);
    $username = trim($_POST['username']);
    $password = trim($_POST['password']);

    if (!checkAgent($agent_id, $agent_md)) {
        redirect('联盟ID或加密字符串不正确！');
    }

    //开始插入config
    $rs = saveConfig($agent_id, $agent_md, $agent_postmd, $cfg_webname, $cfg_indexurl);
    if (!$rs) {
        redirect('保存不成功,请重试！');
    }

    $rs = saveAdmin($username, $password, $agent_md);
    if (!$rs) {
        redirect('账号密码信息保存失败,请重试！');
    }
    ReWriteConfig();
    $rs_write = writeInstallLock();
    if ($rs_write) {
        include('./templates/step-4.html');
    } else {
        redirect('安装出错了,请重试');
    }
    exit();
}
?>
